package com.example.elementui1.controller;

import com.example.elementui1.config.AxiosResult;
import com.example.elementui1.model.User;
import com.example.elementui1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public AxiosResult userList() {
        List<User> users = userService.getUserAll();
        return AxiosResult.success(users);
    }

    @RequestMapping("/add")
    public AxiosResult add(@RequestBody User user) {
        if(user == null || !StringUtils.hasLength(user.getUsername()) ||
        !StringUtils.hasLength(user.getSex()) || user.getAge() == null ||
        !StringUtils.hasLength(user.getAddress())) {
            return AxiosResult.error("用户信息填写不全，请填满信息再提交！", -1);
        }
        userService.add(user);
        return AxiosResult.success(1);
    }

    @RequestMapping("/del")
    public AxiosResult del(Integer id) {
        if(id == null) {
            return AxiosResult.error("参数错误", -1);
        }
        userService.delete(id);
        return AxiosResult.success(1);
    }

}
